package com.auto.survey.base

import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsetsController
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.auto.survey.R
import com.auto.survey.log.AppLogger
import com.auto.survey.permission.PermissionManager
import com.auto.survey.permission.PermissionManager.PermissionExplanationProvider
import com.auto.survey.util.StatusBarHelper
import com.auto.survey.widget.CommonTitle

abstract class BaseActivity :AppCompatActivity() {
    private var viewGroup: ViewGroup? = null
    protected var mContentView: View? = null
    protected var mComment_title: CommonTitle? = null
    protected var mTopBar: RelativeLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        setContentView(getLayoutId())

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.insetsController?.setSystemBarsBehavior(
                WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            )
            // 强制竖屏
            window.setDecorFitsSystemWindows(false)
        } else {
            // 旧版 API 兼容
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }

        PermissionManager.with(this)
            .addPermissionGroup(PermissionManager.PermissionGroup.CAMERA)
            .addPermissionGroup(PermissionManager.PermissionGroup.STORAGE)
            .addPermissionGroup(PermissionManager.PermissionGroup.BLUETOOTH)
            .setForceAllPermissions(true)       //强制要求所有权限
            .setExplanationProvider(object : PermissionExplanationProvider {
                override fun getExplanation(permissions: List<String>): String {
                    val permissionNames = permissions.joinToString { PermissionManager.getPermissionName(it) }
                    return "为了正常使用应用功能，请授予以下权限：$permissionNames"
                }

            }).setDeniedHandler(object : PermissionManager.DeniedPermissionHandler{
                override fun handleDeniedPermissions(result: PermissionManager.PermissionResult) {
                    // 处理被拒绝的权限
                    if (result.hasPermanentlyDenied) {
                        // 有权限被永久拒绝，引导用户到设置页面
                        AlertDialog.Builder(this@BaseActivity)
                            .setMessage("部分权限被永久拒绝，需要到设置中手动开启")
                            .setPositiveButton("去设置") { _, _ -> PermissionManager.openAppSettings(this@BaseActivity) }
                            .setNegativeButton("取消", null)
                            .show()
                    } else {
                        // 权限只是被拒绝，没有永久拒绝
                        Toast.makeText(this@BaseActivity, "部分权限被拒绝", Toast.LENGTH_SHORT).show()
                    }
                }

            }).setCallback(object : PermissionManager.PermissionCallback{
                override fun onAllPermissionsGranted() {
                    // 所有权限已授予
//                    Toast.makeText(this@BaseActivity, "所有权限已授予", Toast.LENGTH_SHORT).show()
                }

                override fun onPermissionsGrantedPartially(result: PermissionManager.PermissionResult) {
                    // 部分权限被授予，可以根据实际情况处理
                    Toast.makeText(this@BaseActivity, "部分权限已授予", Toast.LENGTH_SHORT).show()
                }

                override fun onSomePermissionsDenied(result: PermissionManager.PermissionResult) {
                    // 有权限被拒绝
                    Toast.makeText(this@BaseActivity, "权限申请被拒绝", Toast.LENGTH_SHORT).show()
                }

                override fun onPermissionRequestCancelled() {
                    super.onPermissionRequestCancelled()
                    // 用户取消了权限申请
                    Toast.makeText(this@BaseActivity, "权限申请被取消", Toast.LENGTH_SHORT).show()
                }
            }).request()

        initView()

    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(R.layout.activity_base)
        viewGroup = findViewById(R.id.ll_base_root) as ViewGroup
        mContentView = layoutInflater.inflate(layoutResID, viewGroup)
        mComment_title = findViewById(R.id.comment_title) as CommonTitle
        viewGroup?.setBackgroundColor(Color.WHITE)
        mTopBar = findViewById(R.id.rl_top_bar_mark) as RelativeLayout
        mTopBar?.setVisibility(View.GONE)
        mComment_title?.setVisibility(View.GONE)
        mComment_title?.setTitleColor(Color.WHITE, CommonTitle.TEXT_POSITON_CENTER)
        mComment_title?.setLeftIconColor(R.color.white)
        mComment_title?.setOnBackListener { finish() }


        val statusBarHeight = StatusBarHelper.getStatusBarHeight(this@BaseActivity)
        // 普通日志
        AppLogger.getInstance(this@BaseActivity).d("BaseActivity", "statusBarHeight:"+ statusBarHeight)

        val barLayoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
        mTopBar?.layoutParams = barLayoutParams;

        //透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }

    }


    abstract fun initView()

    abstract fun getLayoutId(): Int
}